<template>
  <div class="booking-records-container">
    <el-card class="booking-card">
      <template #header>
        <div class="card-header">
          <h2>我的预订记录</h2>
          <el-button type="primary" @click="refreshRecords">刷新</el-button>
        </div>
      </template>
      
      <!-- 预订记录筛选 -->
      <div class="filter-container">
        <el-select v-model="statusFilter" placeholder="预订状态" clearable style="width: 150px; margin-right: 10px">
          <el-option label="已预订" value="RESERVED" />
          <el-option label="已取消" value="CANCELLED" />
          <el-option label="已完成" value="COMPLETED" />
        </el-select>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="入住日期开始"
          end-placeholder="入住日期结束"
          style="width: 350px; margin-right: 10px"
        />
        <el-button type="primary" @click="applyFilters">筛选</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </div>
      
      <!-- 预订记录表格 -->
      <el-table 
        :data="filteredRecords" 
        stripe 
        style="width: 100%" 
        v-loading="loading"
        :empty-text="emptyText"
      >
        <el-table-column label="酒店" min-width="180">
          <template #default="scope">
            <div class="hotel-info">
              <div class="hotel-name">{{ scope.row.hotelName || getHotelName(scope.row.hotelId) }}</div>
              <div class="room-type">{{ scope.row.roomType || getRoomType(scope.row.roomId) }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="预订信息" min-width="220">
          <template #default="scope">
            <div>
              <div><b>预订时间:</b> {{ formatDateTime(scope.row.bookingDate) }}</div>
              <div><b>入住日期:</b> {{ formatDate(scope.row.checkInDate) }}</div>
              <div><b>退房日期:</b> {{ formatDate(scope.row.checkOutDate) }}</div>
              <div><b>入住人:</b> {{ scope.row.name }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="总金额" width="120" prop="totalPrice">
          <template #default="scope">
            <span class="price">¥{{ scope.row.totalPrice }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewBookingDetail(scope.row)">
              查看详情
            </el-button>
            <el-button 
              v-if="scope.row.status === 'RESERVED'" 
              type="danger" 
              size="small" 
              @click="cancelBooking(scope.row)"
            >
              取消预订
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRecords"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 预订详情对话框 -->
    <el-dialog v-model="dialogVisible" title="预订详情" width="600px">
      <div v-if="selectedBooking.id" class="booking-detail">
        <div class="detail-header">
          <div class="hotel-name">{{ selectedBooking.hotelName || getHotelName(selectedBooking.hotelId) }}</div>
          <div class="room-type">{{ selectedBooking.roomType || getRoomType(selectedBooking.roomId) }}</div>
        </div>
        
        <el-divider />
        
        <div class="detail-section">
          <div class="detail-item">
            <span class="label">预订编号:</span>
            <span class="value">{{ selectedBooking.id }}</span>
          </div>
          <div class="detail-item">
            <span class="label">预订状态:</span>
            <span class="value">
              <el-tag :type="getStatusType(selectedBooking.status)">
                {{ getStatusText(selectedBooking.status) }}
              </el-tag>
            </span>
          </div>
          <div class="detail-item">
            <span class="label">预订时间:</span>
            <span class="value">{{ formatDateTime(selectedBooking.bookingDate) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">入住日期:</span>
            <span class="value">{{ formatDate(selectedBooking.checkInDate) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">退房日期:</span>
            <span class="value">{{ formatDate(selectedBooking.checkOutDate) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">入住人:</span>
            <span class="value">{{ selectedBooking.name }}</span>
          </div>
          <div class="detail-item">
            <span class="label">联系电话:</span>
            <span class="value">{{ selectedBooking.phone }}</span>
          </div>
          <div class="detail-item">
            <span class="label">特殊要求:</span>
            <span class="value">{{ selectedBooking.specialRequests || '无' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">总金额:</span>
            <span class="value price">¥{{ selectedBooking.totalPrice }}</span>
          </div>
        </div>
        
        <div class="detail-actions" v-if="selectedBooking.status === 'RESERVED'">
          <el-button type="danger" @click="cancelSelectedBooking">取消预订</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import request from '@/utils/request.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();
const bookingRecords = ref([]);
const hotelCache = ref({});
const roomCache = ref({});
const loading = ref(false);
const dialogVisible = ref(false);
const selectedBooking = ref({});
const statusFilter = ref('');
const dateRange = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalRecords = ref(0);
const emptyText = ref('暂无预订记录');

// 添加自动刷新定时器
const refreshTimer = ref(null);

// 根据筛选条件过滤记录
const filteredRecords = computed(() => {
  let records = [...bookingRecords.value];
  
  // 按状态筛选
  if (statusFilter.value) {
    records = records.filter(record => record.status === statusFilter.value);
  }
  
  // 按日期范围筛选
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = dateRange.value[0];
    const endDate = dateRange.value[1];
    
    if (startDate && endDate) {
      records = records.filter(record => {
        const checkInDate = new Date(record.checkInDate);
        return checkInDate >= startDate && checkInDate <= endDate;
      });
    }
  }
  
  // 计算总记录数
  totalRecords.value = records.length;
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return records.slice(start, end);
});

// 获取酒店名称
const getHotelName = (hotelId) => {
  // 优先使用API返回的hotelName字段，如果没有再使用缓存
  const booking = bookingRecords.value.find(b => b.hotelId === hotelId);
  if (booking && booking.hotelName) {
    return booking.hotelName;
  }
  return hotelCache.value[hotelId]?.name || `酒店 #${hotelId}`;
};

// 获取房间类型
const getRoomType = (roomId) => {
  // 优先使用API返回的roomType字段，如果没有再使用缓存
  const booking = bookingRecords.value.find(b => b.roomId === roomId);
  if (booking && booking.roomType) {
    return booking.roomType;
  }
  return roomCache.value[roomId]?.room_type || `房间 #${roomId}`;
};

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'RESERVED': return 'primary';
    case 'CANCELLED': return 'danger';
    case 'COMPLETED': return 'success';
    default: return 'info';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'RESERVED': return '已预订';
    case 'CANCELLED': return '已取消';
    case 'COMPLETED': return '已完成';
    default: return '未知状态';
  }
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleDateString();
};

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  const date = new Date(dateTimeStr);
  return date.toLocaleString();
};

// 加载预订记录
const loadBookingRecords = async () => {
  loading.value = true;
  emptyText.value = '加载中...';
  
  try {
    // 从localStorage获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('xm-pro-user'));
    if (!userInfo) {
      ElMessage.error('请先登录');
      router.push('/login');
      return;
    }
    
    // 直接使用用户ID获取预订记录
    const bookingRes = await request.get(`/booking/listByUserId/${userInfo.id}`);
    if (bookingRes.code === '200') {
      bookingRecords.value = bookingRes.data || [];
      console.log('预订记录:', bookingRecords.value); // 添加调试日志
      
      // 如果返回的数据已经包含酒店名称和房间类型，就不需要额外请求了
      const hasRelatedData = bookingRecords.value.length > 0 && 
                            (bookingRecords.value[0].hotelName || bookingRecords.value[0].roomType);
      
      if (!hasRelatedData) {
        // 仅在需要时加载酒店和房间信息
        await loadHotelAndRoomInfo();
      }
    } else {
      ElMessage.error(bookingRes.msg || '获取预订记录失败');
    }
    
    emptyText.value = '暂无预订记录';
  } catch (error) {
    console.error('加载预订记录失败', error);
    ElMessage.error('加载预订记录失败，请稍后重试');
    emptyText.value = '加载失败，请重试';
  } finally {
    loading.value = false;
  }
};

// 加载酒店和房间信息
const loadHotelAndRoomInfo = async () => {
  try {
    // 提取所有酒店ID和房间ID
    const hotelIds = [...new Set(bookingRecords.value.map(record => record.hotelId))];
    const roomIds = [...new Set(bookingRecords.value.map(record => record.roomId))];
    
    // 加载酒店信息
    await Promise.all(hotelIds.map(async (hotelId) => {
      if (!hotelCache.value[hotelId]) {
        const res = await request.get(`/hotel/selectById/${hotelId}`);
        hotelCache.value[hotelId] = res.data;
      }
    }));
    
    // 加载房间信息
    await Promise.all(roomIds.map(async (roomId) => {
      if (!roomCache.value[roomId]) {
        const res = await request.get(`/room/selectById/${roomId}`);
        roomCache.value[roomId] = res.data;
      }
    }));
  } catch (error) {
    console.error('加载酒店和房间信息失败', error);
  }
};

// 查看预订详情
const viewBookingDetail = (booking) => {
  selectedBooking.value = { ...booking };
  dialogVisible.value = true;
};

// 取消预订
const cancelBooking = (booking) => {
  ElMessageBox.confirm(
    '确定要取消此预订吗？取消后将无法恢复。',
    '取消预订',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const updateData = {
        ...booking,
        status: 'CANCELLED'
      };
      await request.put(`/booking/update/${booking.id}`, updateData);
      ElMessage.success('预订已取消');
      loadBookingRecords(); // 重新加载预订记录
    } catch (error) {
      console.error('取消预订失败', error);
      ElMessage.error('取消预订失败，请稍后重试');
    }
  }).catch(() => {
    // 用户取消操作，不做任何处理
  });
};

// 取消当前选中的预订
const cancelSelectedBooking = () => {
  cancelBooking(selectedBooking.value);
  dialogVisible.value = false;
};

// 定时刷新逻辑
const startAutoRefresh = () => {
  // 清除可能存在的定时器
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value);
  }
  
  // 设置新的定时器，每60秒刷新一次数据
  refreshTimer.value = setInterval(() => {
    loadBookingRecords();
  }, 60000); // 60秒
};

// 清除定时器
const stopAutoRefresh = () => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value);
    refreshTimer.value = null;
  }
};

// 应用筛选条件
const applyFilters = () => {
  currentPage.value = 1; // 重置页码
};

// 重置筛选条件
const resetFilters = () => {
  statusFilter.value = '';
  dateRange.value = [];
  currentPage.value = 1;
};

// 处理页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};

// 处理每页显示数量变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
};

// 初始化加载
onMounted(() => {
  loadBookingRecords();
  startAutoRefresh();
});

// 组件销毁时清除定时器
onUnmounted(() => {
  stopAutoRefresh();
});

// 修改刷新记录方法
const refreshRecords = () => {
  loadBookingRecords();
  // 显示刷新成功消息
  ElMessage.success('数据已刷新');
};
</script>

<style scoped>
.booking-records-container {
  padding: 20px;
}

.booking-card {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.hotel-info {
  display: flex;
  flex-direction: column;
}

.hotel-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.room-type {
  color: #606266;
  font-size: 13px;
}

.price {
  color: #ff6700;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 详情样式 */
.booking-detail {
  padding: 10px;
}

.detail-header {
  margin-bottom: 15px;
}

.detail-header .hotel-name {
  font-size: 18px;
  font-weight: bold;
}

.detail-section {
  margin: 20px 0;
}

.detail-item {
  display: flex;
  margin-bottom: 15px;
}

.detail-item .label {
  width: 100px;
  color: #606266;
}

.detail-item .value {
  flex: 1;
  font-weight: bold;
}

.detail-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>